package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

public class StrokeImageView extends AppCompatImageView {
    public StrokeImageView(Context context) {
        super(context);
    }

    public StrokeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public StrokeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //系统将XML解析出对应的控件实例时候的回调
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Paint paint = new Paint();
        paint.setColor(Color.CYAN);

        setStateDrawable(this, paint);
    }

    private void setStateDrawable(StrokeImageView v, Paint paint) {
        BitmapDrawable bd = (BitmapDrawable) v.getDrawable();
        Bitmap srcBitmap = bd.getBitmap();

        //制作纯色背景
        Bitmap bitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(srcBitmap.extractAlpha(), 0, 0, paint);

        //添加状态
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new BitmapDrawable(bitmap));

        v.setBackgroundDrawable(stateListDrawable);
    }


}
